<template>
	<div class="bigDiv">
		<el-form :model="queryParams" ref="queryForm" :inline="true" label-width="88px">
			<div class="topNav">
				<el-button type="text" @click="handlePushAll" :disabled="listButtonClick">批量审批</el-button>
				<el-button type="text" @click="handleFailAll" :disabled="listButtonClick">批量驳回</el-button>
				<el-button type="text" icon="el-icon-search" @click="handleQuery" style="float:right;">搜索</el-button>
				<el-button type="text" icon="el-icon-refresh" @click="resetQuery" style="float:right;">重置</el-button>
			</div>
			<el-form-item label="sku" prop="sku">
				<el-input v-model="queryParams.sku" placeholder="请输入商品sku" clearable size="small"
					@keyup.enter.native="handleQuery" />
			</el-form-item>
			<!-- <el-form-item label="流程名称" prop="taskName">
				<el-input v-model="queryParams.taskName" placeholder="请输入流程名称" clearable size="small"
					@keyup.enter.native="handleQuery" />
			</el-form-item> -->
			<el-form-item label="供应商" >
				<el-select v-model="queryParams.supplierId" placeholder="请选择一个供应商" clearable size="small"
					@keyup.enter.native="handleQuery">
					<el-option v-for="item in supplierList" :value="item.supplierId" :label="item.supplierName">{{ item.supplierName }}</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="一级分类" prop="primaryCategory">
				<el-select v-model="queryParams.primaryCategory" size="small" filterable
					@change="changePrimaryCategory">
					<el-option v-for="item in primaryCategory" :key="item.id" :label="item.categoryName"
						:value="item.id">{{ item.categoryName }}
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="二级分类" prop="secondaryCategory">
				<el-select v-model="queryParams.secondaryCategory" size="small" filterable
					@change="changeSecondaryCategory">
					<el-option v-for="item in secondaryCategory" :key="item.id" :label="item.categoryName"
						:value="item.id">
						{{ item.categoryName }}
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="三级分类" prop="tertiaryCategory">
				<el-select v-model="queryParams.tertiaryCategory" size="small" filterable
					@change="changeTertiaryCategory">
					<el-option v-for="item in tertiaryCategory" :key="item.id" :label="item.categoryName"
						:value="item.id">
						{{ item.categoryName }}
					</el-option>
				</el-select>
			</el-form-item>
		</el-form>
		<el-table v-loading="loading" :data="tastList" @selection-change="handleSelectionChange" ref="multipleTable" height="calc(100vh - 300px)">
			<el-table-column type="selection" fixed width="55"></el-table-column>
			<!-- <el-table-column label="供应商" align="center" prop="supplierName" />
			<el-table-column label="类型" align="center" prop="sku">
				<template slot-scope="scope">
					<span v-if="scope.row.goodsListId == ''">单个商品</span>
					<span v-else>多个商品</span>
				</template>
			</el-table-column>
			<el-table-column label="流程名称" align="center" prop="instanceName" />
			<el-table-column label="任务节点名称" align="center" prop="name" />
			<el-table-column label="提报人" align="center" prop="createdName" />
			<el-table-column label="任务创建时间" align="center" prop="createdDate" /> -->

			<el-table-column label="商品名称" align="center" prop="goodsName" width="250">
				<template slot-scope="scope">
					<el-tooltip :content="scope.row.goodsItem? scope.row.goodsItem.goodsName : ''" placement="bottom" effect="dark" class="goodsNameBox">
						<div>{{ scope.row.goodsItem? scope.row.goodsItem.goodsName : '' }}</div>
					</el-tooltip>
				</template>
			</el-table-column>

			<el-table-column label="商品分类" align="center" width="350">
				<template slot-scope="scope">
					{{ scope.row.goodsItem ? scope.row.goodsItem.primaryCategoryName : '' }}
					<span class="divider">/</span>
					{{ scope.row.goodsItem? scope.row.goodsItem.secondaryCategoryName : '' }}
					<span class="divider">/</span>
					{{ scope.row.goodsItem? scope.row.goodsItem.tertiaryCategoryName : '' }}
				</template>
			</el-table-column>
			<el-table-column label="计量单位" align="center" prop="saleUnit">
				<template slot-scope="scope">
					{{ scope.row.goodsItem ? scope.row.goodsItem.saleUnit : '' }}
				</template>
			</el-table-column>
			<el-table-column label="优采销售价(元)" align="center" prop="goodsPrice" width="88">
				<template slot-scope="scope">
					<span class="price">
						{{ scope.row.goodsItem ? priceCalc(scope.row.goodsItem.goodsPrice) : '' }}
					</span>
				</template>
			</el-table-column>
			<!-- <el-table-column label="优采未税价(元)" align="center" prop="excludeTaxPrice" width="88">
				<template slot-scope="scope">
					{{ priceCalc(scope.row.goodsItem.excludeTaxPrice) }}
				</template>
			</el-table-column> -->
			<el-table-column label="官网价(元)" align="center" prop="officialPrice">
				<template slot-scope="scope">
					<span class="price">
						{{ scope.row.goodsItem ? scope.row.goodsItem.officialPrice : '' }}
					</span>
				</template>
			</el-table-column>
			<!-- <el-table-column label="协议价(元)" align="center" prop="goodsPrice" width="88">
				<template slot-scope="scope">
					<span>
						{{ priceCalc(scope.row.goodsItem.agreementPrice) }}
					</span>
				</template>
			</el-table-column> -->
			<el-table-column label="折扣率" align="center" width="88">
				<template slot-scope="scope">
					{{ scope.row.goodsItem ? discountRateCalc(scope.row.goodsItem) : '' }}
				</template>
			</el-table-column>
			<!-- <el-table-column label="电商未税价(元)" align="center" prop="excludeTaxPrice" width="88">
				<template slot-scope="scope">
					<span>
						{{ priceCalc(scope.row.goodsItem.initExcludeTaxPrice) }}
					</span>
				</template>
			</el-table-column> -->
			<el-table-column label="品牌" align="center" prop="brandName" width="180">
				<template slot-scope="scope">
					{{ scope.row.goodsItem ? scope.row.goodsItem.brandName : '' }}
				</template>
			</el-table-column>
			<el-table-column label="sku" align="center" prop="sku" width="150">
				<template slot-scope="scope">
					<el-tooltip :content="scope.row.goodsItem ? scope.row.goodsItem.sku : ''" placement="bottom" effect="dark" class="goodsNameBox">
						<div>{{ scope.row.goodsItem ? scope.row.goodsItem.sku : '' }}</div>
					</el-tooltip>
				</template>
			</el-table-column>
			<!-- <el-table-column label="库存" align="center" prop="goodsStock">
				<template slot-scope="scope">
					{{ scope.row.goodsItem.goodsStock }}
				</template>
			</el-table-column> -->
			<el-table-column label="供应商" align="center" prop="supplierName" width="200">
				<template slot-scope="scope">
					{{ scope.row.goodsItem ? scope.row.goodsItem.supplierName : '' }}
				</template>
			</el-table-column>
			<el-table-column label="导入时间" align="center" prop="createTime" width="100">
				<template slot-scope="scope">
					{{ scope.row.goodsItem ? scope.row.goodsItem.createTime : '' }}
				</template>
			</el-table-column>

			<el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
				<template slot-scope="scope">
					<el-button size="mini" type="text" icon="el-icon-edit" @click="examineAndApprove(scope.row)">审批
					</el-button>
				</template>
			</el-table-column>
		</el-table>

		<el-pagination v-show="total>0" :total="total" :current-page="queryParams.pageNum" background
			:page-size="queryParams.pageSize" @current-change="changePage" @size-change="sizeChange"
			layout="total, sizes, prev, pager, next, jumper" class="page-box" style="text-align: right">
		</el-pagination>

		<!-- 审批对话框 -->
		<el-dialog title="驳回审批" :visible.sync="open" v-if="open" width="500px" append-to-body>
			<div>
				<el-input type="textarea" :rows="10" placeholder="驳回原因" v-model="textarea"></el-input>
			</div>

			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="doFail">确 定</el-button>
				<el-button @click="open = false">取 消</el-button>
			</div>
		</el-dialog>

		<el-dialog title="批量操作" :visible.sync="dialogReimportVisible" width="30%" :before-close="stopReimport">
			<el-progress :percentage="percentage" text-inside :stroke-width="20"></el-progress>
			<div style="text-align: center;">
				<span>已执行 {{ count }}/{{ reImportTotal }}</span>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="stopReimport">取 消</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import {
		listTaskAll,
		formDataShow,
		formDataSave
	} from "@/api/activiti/supplierTask";
	import { allSupplier } from "@/api/supplierActivity/task"
	import {
		queryGodCategoryZtreeAsyn
	} from "@/api/supplier.api";
	import leaveHistoryForm from "@/views/activiti/workflow/leave/leaveHistoryForm";
	import tools from "@/tools"

	export default {
		name: "Leave",
		components: {
			leaveHistoryForm
		},
		data() {
			return {
				id: '',
				definitionKey: '',
				businessKey: '',
				// 遮罩层
				loading: true,
				// 选中数组
				ids: [],
				// 非单个禁用
				single: true,
				// 非多个禁用
				multiple: true,
				// 显示搜索条件
				showSearch: true,
				// 总条数
				total: 0,
				// 请假表格数据
				tastList: [],
				// 弹出层标题
				title: "",
				// 是否显示弹出层
				open: false,
				// 查询参数
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					sku: undefined,
					taskName: undefined,
					supplierId: undefined,
					primaryCategory: undefined,
					secondaryCategory: undefined,
					tertiaryCategory: undefined,
				},
				primaryCategory: [],
				secondaryCategory: [],
				tertiaryCategory: [],
				supplierList: [],
				// 表单参数
				form: {
					formData: []
				},
				// 表单校验
				rules: {},
				multipleSelection: [],
				saveList: [],
				stop: false,
				textarea: "",
				count: 0,
				dialogReimportVisible: false
			};
		},
		computed: {
			listButtonClick() {
				return this.multipleSelection.length <= 0;
			},
			reImportTotal() {
				return this.multipleSelection.length
			},
			percentage() {
				if (this.count == 0) return 0
				return parseFloat(((this.count / this.multipleSelection.length) * 100).toFixed(2))
			}
		},
	created() {
		const PrimaryCategory = this.$tools.localRead("taskAll-primaryCategory") || undefined;
		const SecondaryCategory = this.$tools.localRead("taskAll-secondaryCategory") || undefined;
		const TertiaryCategory = this.$tools.localRead("taskAll-tertiaryCategory") || undefined;

		this.queryParams.pageNum = parseInt(this.$tools.localRead("taskAll-pageNum") || 1);
		this.queryParams.pageSize = parseInt(this.$tools.localRead("taskAll-pageSize") || 10);
		this.queryParams.supplierId = this.$tools.localRead("taskAll-supplierId") || undefined;
		this.queryParams.sku = this.$tools.localRead("taskAll-sku") || undefined;
		this.queryParams.primaryCategory = PrimaryCategory;
		this.queryParams.secondaryCategory = SecondaryCategory;
		this.queryParams.tertiaryCategory = TertiaryCategory	
	
		this.getList();
		this.getSupplier();
		// 初始化分类列表
		this.primaryCategory = [];
		queryGodCategoryZtreeAsyn("", 1).then((res) => {
			this.primaryCategory = res;
		});

		if (PrimaryCategory) { 
			queryGodCategoryZtreeAsyn(PrimaryCategory, 1).then((res) => {
					this.secondaryCategory = res;
				});
		}

		if (SecondaryCategory) { 
			queryGodCategoryZtreeAsyn(SecondaryCategory, 1).then((res) => {
					this.tertiaryCategory = res;
				});
		}

		},
	methods: {
		changePrimaryCategory(id) {
				this.queryParams.secondaryCategory = "";
				this.secondaryCategor = [];
				this.tertiaryCategory = [];
				queryGodCategoryZtreeAsyn(id, 1).then((res) => {
					this.secondaryCategory = res;
				});
				this.queryParams.tertiaryCategory = "";

				this.primaryCategory.map((row) => {
					if (row.id == id) {
						this.$nextTick(() => {
							this.queryParams.primaryCategory = row.id;
						});
					}
				});
			},
			changeSecondaryCategory(id) {
				this.queryParams.tertiaryCategory = "";
				this.tertiaryCategory = [];
				queryGodCategoryZtreeAsyn(id, 1).then((res) => {
					this.tertiaryCategory = res;
				});
				this.secondaryCategory.map((row) => {
					if (row.id == id) {
						this.$nextTick(() => {
							this.queryParams.secondaryCategory = row.id;
						});
					}
				});
			},
			changeTertiaryCategory(id) {
				this.tertiaryCategory.map((row) => {
					if (row.id == id) {
						this.$nextTick(() => {
							this.queryParams.tertiaryCategory = row.id;
						});
					}
				});
			},
			getSupplier() {
				allSupplier().then(res => {
					this.supplierList = res
				})
			},
			changePage(page) {
				this.queryParams.pageNum = page
				this.$tools.localSave("taskAll-pageNum", page);
				this.getList()
			},
			sizeChange(size) {
				this.queryParams.pageSize = size
				this.$tools.localSave("taskAll-pageSize", size);
				this.getList()
			},
			/** 搜索按钮操作 */
			handleQuery() {
				this.queryParams.pageNum = 1;
				this.getList();
			},
			/** 重置按钮操作 */
			resetQuery() {
				this.queryParams= {
					pageNum: 1,
					pageSize: 10,
					sku: undefined,
					taskName: undefined,
					supplierId: undefined,
					primaryCategory: undefined,
					secondaryCategory: undefined,
					tertiaryCategory: undefined,
				} 
				// 重置查询参数 
				this.$tools.localSave("taskAll-sku", undefined);
				this.$tools.localSave("taskAll-supplierId", undefined);
				this.$tools.localSave("taskAll-primaryCategory", undefined); 
				this.$tools.localSave("taskAll-secondaryCategory", undefined); 
				this.$tools.localSave("taskAll-tertiaryCategory", undefined); 
				this.handleQuery();
			},
			lookDetail(row) {
				localStorage.setItem("type", 1);
				this.$router.push({
					path: "/activiti?type=1&deploymentId=" + row.id
				})
			},
			/** 查询请假列表 */
			getList() {
				this.loading = true; 
				this.$tools.localSave("taskAll-supplierId", this.queryParams.supplierId);
				this.$tools.localSave("taskAll-sku", this.queryParams.sku);
				this.$tools.localSave("taskAll-primaryCategory", this.queryParams.primaryCategory);
				this.$tools.localSave("taskAll-secondaryCategory", this.queryParams.secondaryCategory);
				this.$tools.localSave("taskAll-tertiaryCategory", this.queryParams.tertiaryCategory);

				listTaskAll(this.queryParams).then(response => {
					this.tastList = response.rows;
					this.total = response.total;
					this.loading = false;
				});
			},

			// 取消按钮
			cancel() {
				this.open = false;
				this.reset();
			},
			// 表单重置
			reset() {
				this.definitionKey = '',
					this.businessKey = '',
					this.form = {
						formData: [],
					};
				this.resetForm("form");
			},

			/** 审批按钮操作 */
			examineAndApprove(row) {
				if (row.goodsListId == "") {
					this.$router.push({
						path: "/activitiorder_supplier?supplierId=" + row.supplierId + "&sku=" + row.sku +
							"&taskId=" + row.id + "&definitionKey=" + row
							.definitionKey + "&businessKey=" + row.businessKey + "&type=all"
					})
				} else {
					this.$router.push({
						path: "/activitiorder_supplier_list?supplierId=" + row.supplierId + "&goodsListId=" + row
							.goodsListId + "&taskId=" + row.id + "&definitionKey=" + row
							.definitionKey + "&businessKey=" + row.businessKey + "&type=all"
					})
				}

			},
			/** 提交按钮 */
			submitForm() {
				formDataSave(this.id, this.form.formData).then(response => {
					this.msgSuccess("审批成功");
					this.open = false;
					this.getList();
				});
			},
			handleSelectionChange(val) {
				this.multipleSelection = val;
			},
			// 批量提交
			handlePushAll() {
				if (this.multipleSelection.length <= 0) {
					return this.$message.error({
						message: "还未选择任何数据"
					})
				}
				this.$confirm('确认审核通过所选审批流？')
					.then(_ => {
						this.saveList = [...this.multipleSelection];
						this.stop = false;
						this.dialogReimportVisible = true;
						this.start(0, "同意");
					})
					.catch(_ => {});
			},
			// 批量驳回
			handleFailAll() {
				if (this.multipleSelection.length <= 0) {
					return this.$message.error({
						message: "还未选择任何行"
					})
				}
				this.open = true;
			},
			doFail() {
				this.$confirm("确认驳回所选审批流？")
					.then(_ => {
						this.open = false
						this.dialogReimportVisible = true;
						this.saveList = [...this.multipleSelection];
						this.stop = false;
						this.saveList = [...this.multipleSelection];
						this.start(1, this.textarea);
					})
					.catch(_ => {});
			},
			start(radio, textarea) {
				setTimeout(() => {
					if (!this.stop) {
						const row = this.saveList.shift();
						// 获取表单
						formDataShow(row.id).then(response => {
							var datas = response;
							var formData = [];
							for (var i = 0; i < datas.length; i++) {
								var strings = datas[i].split('--__!!')
								var controlValue = null
								var controlDefault = null
								switch (strings[1]) {
									case 'radio':
										controlValue = radio;
										controlDefault = strings[4]
										break;
									case 'textarea':
										controlValue = textarea;
								}
								formData.push({
									controlId: strings[0],
									controlType: strings[1],
									controlLable: strings[2],
									controlIsParam: strings[3],
									controlValue: controlValue,
									controlDefault: controlDefault
								})
							}
							// 执行保存表单动作
							formDataSave(row.id, formData).then(response => {
								if (response.code == 200) {
									this.count++;
								}
								if (this.saveList.length > 0) {
									this.start(radio, textarea);
								} else {
									const countFail = this.reImportTotal - this.count;
									const count = this.count;
									this.dialogReimportVisible = false
									this.count = 0;
									this.multipleSelection = [];
									this.saveList = [];
									this.$refs.multipleTable.clearSelection();
									this.getList();
									this.$message.success({
										message: `操作完成。成功${count}条,失败${countFail}条。`,
										duration: 0,
										showClose: true
									})
								}
							});
						});

					}
				}, 1000)
			},
			stopReimport() {
				this.stop = true
				this.dialogReimportVisible = false
				this.count = 0;
				this.multipleSelection = [];
				this.saveList = [];
				this.$refs.multipleTable.clearSelection();
				this.getList();
				this.$message.error({
					message: "已停止"
				})
			},
			priceCalc(price) {
				if (price) return price.toFixed(2);
			},
			// 计算折扣率
			discountRateCalc(row) {
				const goodsPrice = row.agreementPrice
				const officialPrice = row.officialPrice
				if (goodsPrice == "" || goodsPrice == 0) {
					return "wait..."
				}
				if (officialPrice == "" || officialPrice == 0 || officialPrice == null || officialPrice == undefined) {
					return "";
				}
				return (tools.accDiv(goodsPrice, officialPrice) * 100).toFixed(2) + "%"
			}
		}
	};
</script>

<style lang="scss" scoped>
	.page-box {
		padding: 10px 0;
	}
	.price {
		color: #ff4d4f;
	}
	
	.goodsNameBox {
		overflow: hidden;
		max-width: 100%;
		white-space: nowrap;
		height: 25px;
		text-overflow: ellipsis;
	}
	::v-deep {
		.el-table .el-table__cell{
			padding:0px !important;
		}
	}
</style>
